I am trying to fetch data of different collections from MongoDB. I do this with Node.js and promises. Here is some basic code:
await Promise.all(
["a", "b", "c"].map(async (collection) => {
const query: any = { "_id": { $in: ids} }
// I just use toArray for demonstration purposes
const data = await this.db!.collection(collection).find(query).toArray()
for (let i = 0; i < data.length; i++) {
const document = data[i]
// Do something...
}
console.log(collection)
return true
})
)
console.log("done")
I do this for eight collections (a, b, ..., h). The data gets fetched from the database and processed correctly in an acceptable amount of time. Then it prints the name for each collection. But it doesn't continue. It doesn't finish the promise and go to the done log.
The method gets called in a JS-Worker task. What could be the problem here? I never had problems with promises and bigger amount of data yet.
This is actually a synchronous execution. It will not go to the next collection until the previous db call is finished. The arrow function should return a promise instead.
The solution is to rearrange the code in this way-
async function callDb(collection) {
const query: any = { "_id": { $in: ids} }
// I just use toArray for demonstration purposes
const data = await this.db!.collection(collection).find(query).toArray()
for (let i = 0; i < data.length; i++) {
const document = data[i]
// Do something...
}
console.log(collection)
return true
}
await Promise.all(
["a", "b", "c"].map(callDb)
)
console.log("done")